//
//  YsNoteSDKNetWork.m
//  YsNoteSDK
//
//  Created by 宋宏康 on 2020/3/21.
//

#import "YsNoteSDKNetWorkManager.h"
#import "YsNoteSDKHeader.h"
#import <AFNetworking/AFNetworking.h>
#import <YYKit/YYKit.h>


@implementation YsNoteSDKNetWorkManager
+ (NSURLSessionDataTask *)postHttpDataWithUrlStr:(NSString *)url dic:(NSDictionary *)dic successBlock:(SuccessBlock)successBlock failureBlock:(FailedBlock)failureBlock
{
    NSCParameterAssert(successBlock);
    NSCParameterAssert(failureBlock);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer]; // 请求参数
    [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [requestSerializer setValue:YsNoteSDKUserDefaultsObjectForKey(@"kYsNoteSDKKeyloginToken") forHTTPHeaderField:@"x-auth-token"];
    [manager setRequestSerializer:requestSerializer]; // 请求格式是json
    
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
    [responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]];
    [manager setResponseSerializer:responseSerializer]; // 返回的格式是json

   NSURLSessionDataTask *task = [manager POST:url parameters:dic headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        YsToolsManagerResultModel *model = [YsToolsManagerResultModel modelWithJSON:responseObject];
        if (model.isSuccessful) {
            successBlock(model);
        }else{
            NSError *error = [NSError errorWithDomain:@"cn.YsNetWorkManage.errormsg" code:[model.code intValue] userInfo:@{NSLocalizedDescriptionKey : model.errorMsg}];
            failureBlock(error);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        /** 这里是处理事件的回调 */
        failureBlock(error);
    }];
   return task;
}

+ (NSURLSessionDataTask *)getHttpDataWithUrlStr:(NSString *)url dic:(NSDictionary *)dic successBlock:(SuccessBlock)successBlock failureBlock:(FailedBlock)failureBlock
{
    NSCParameterAssert(successBlock);
    NSCParameterAssert(failureBlock);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer]; // 请求参数
    [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [requestSerializer setValue:YsNoteSDKUserDefaultsObjectForKey(@"kYsNoteSDKKeyloginToken") forHTTPHeaderField:@"x-auth-token"];
    [manager setRequestSerializer:requestSerializer]; // 请求格式是json
    
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
    [responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]];
    [manager setResponseSerializer:responseSerializer]; // 返回的格式是json
   NSURLSessionDataTask *task =  [manager GET:url parameters:dic headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
       YsToolsManagerResultModel *model = [YsToolsManagerResultModel modelWithJSON:responseObject];
        if (model.isSuccessful) {
            successBlock(model);
        }else{
            NSError *error = [NSError errorWithDomain:@"cn.YsNetWorkManage.errormsg" code:[model.code intValue] userInfo:@{NSLocalizedDescriptionKey : model.errorMsg}];
            failureBlock(error);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        /** 这里是处理事件的回调 */
        failureBlock(error);
    }];
   return task;
}


+ (NSURLSessionDownloadTask *)downloadHttpDataWithUrlStr:(NSString *)url withDownloadPath:(NSString *)path completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{
    NSCParameterAssert(url);
    NSCParameterAssert(path);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer]; // 请求参数
    [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [requestSerializer setValue:YsNoteSDKUserDefaultsObjectForKey(@"kYsNoteSDKKeyloginToken") forHTTPHeaderField:@"x-auth-token"];
    [manager setRequestSerializer:requestSerializer]; // 请求格式是json
    
    AFJSONResponseSerializer *responseSerializer = [AFJSONResponseSerializer serializer];
    [responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil]];
    [manager setResponseSerializer:responseSerializer]; // 返回的格式是json
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:1 timeoutInterval:15];
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:[path stringByAppendingPathComponent:response.suggestedFilename]];
    } completionHandler:completionHandler];
    [task resume];
   return task;
}


+ (NSURLSessionDataTask *)uploadFetchWayWithuid:(NSString *)uid
                                        success:(void (^)(YsToolsManagerResultModel *result))successfull
                                           fail:(void (^)(NSError *error))failed
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:uid forKey:@"uid"];
    NSURLSessionDataTask *task = [self postHttpDataWithUrlStr:YsNoteSDKUploadServerLink(    ways/ways/upload/fetchWay) dic:dict successBlock:successfull failureBlock:failed];
    return task;
}

+ (NSURLSessionDataTask *)noteBooks:(NSString *)user_fkcode
success:(void (^)(YsToolsManagerResultModel *result))successfull
   fail:(void (^)(NSError *error))failed
{
   NSURLSessionDataTask *task = [self getHttpDataWithUrlStr:YsNoteSDKUrlLink(mb/new/note-book/note-book-list) dic:nil successBlock:successfull failureBlock:failed];
    return task;
}

+ (NSURLSessionDataTask *)requestGetLoginInSchoohWithUserAccountCode:(NSString *)accountCode
success:(void (^)(YsToolsManagerResultModel *result))successful
   fail:(void (^)(NSError *error))failed
{
    NSDictionary *dict = @{@"user_account_code":accountCode};
   NSURLSessionDataTask *task = [self getHttpDataWithUrlStr:YsNoteSDKUrlLink(mb/user-account-code/login) dic:dict successBlock:successful failureBlock:failed];
    return task;
}


+ (NSURLSessionDataTask *)userNoteBooksList:(NSString *)user_fkcode
                                book_fkcode:(NSString *)book_fkcode
                                    page_no:(NSString *)page_no
                                  page_size:(NSString *)page_size
                                  note_type:(NSString *)note_type
                                    success:(void (^)(YsToolsManagerResultModel *result))successfull
                                       fail:(void (^)(NSError *error))failed
{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:user_fkcode forKey:@"user_fkcode"];
    [dict setValue:book_fkcode forKey:@"book_fkcode"];
    [dict setValue:@([page_no integerValue]) forKey:@"page_no"];
    [dict setValue:@([page_size integerValue]) forKey:@"page_size"];
    [dict setValue:@(NO) forKey:@"page"];
    [dict setValue:@([note_type integerValue]) forKey:@"note_type"];
    NSURLSessionDataTask *task = [self postHttpDataWithUrlStr:YsNoteSDKUrlLink(mb/new/note-book/user/note-book/notes) dic:dict successBlock:successfull failureBlock:failed];
        return task;
}

+ (NSURLSessionDownloadTask *)downloadURL:(NSString *)downloadURL
                                     path:(NSString *)path
                        completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler;
{
  NSURLSessionDownloadTask *task = [self downloadHttpDataWithUrlStr:downloadURL withDownloadPath:path completionHandler:completionHandler];
    return task;
}
@end
